package main

import (
	"os"
	"fmt"
)

func main() {
	maze := readMaze()
	for _, row := range maze {
		for _, val := range row {
			fmt.Printf("%d", val)
		}
		fmt.Println()
	}
	//fmt.Println(maze)
	steps := walk(maze, point{0, 0}, point{len(maze) - 1, len(maze[0]) - 1})
	//steps := walk(maze, point{0, 0}, point{2, 2})

	for _,row := range steps{
		for _,val:= range row {
			fmt.Printf("%3d",val)
		}
		fmt.Println()
	}
	//fmt.Println(walk)
}

type point struct {
	i, j int
}

var dirs = [4] point{
	{-1, 0}, {0, -1}, {1, 0}, {0, 1},
}

func (p point) add(r point) point {

	return point{p.i + r.i, p.j + r.j}
}
func (p point) at(grid [][]int) (int, bool) {
	if p.i < 0 || p.i >= len(grid) {
		return 0, false
	}
	if p.j < 0 || p.j >= len(grid[p.i]) {
		return 0, false
	}
	return grid[p.i][p.j], true
}
func walk(maze [][]int, start, end point) [][]int {
	steps := make([][]int, len(maze))
	for i := range steps {
		steps[i] = make([]int, len(maze[i]))
	}

	Q := []point{start}//创建Q 队列 有下一步就往队列里塞
	for len(Q) > 0 {
		cur := Q[0]//当前 point
		Q = Q[1:]

		if cur == end{//发现终点 退出
			break
		}
		//dirs 代表四种方向
		for _, dir := range dirs {
			next := cur.add(dir)
			value, ok := next.at(maze) //
			if !ok || value == 1 { // ==1 说明撞墙了
				continue
			}

			value, ok = next.at(steps)//steps 初始都是0 不为0 的位置是走过的
			if !ok || value != 0 { // != 0 说明走过了
				continue
			}

			if next == start {//走回起点
				continue
			}

			curSteps, _ := cur.at(steps)//找到当前值在 steps得值
			steps[next.i][ next.j] = curSteps + 1

			Q = append(Q, next)

			//maze add next is 0
			//and steps at next is 0
			//and steps != start
		}

	}
	return steps

}
func readMaze() [][]int {
	var fileName = "maze/maze.in"
	file, error := os.Open(fileName)
	if error != nil {
		panic(error)
	}
	//reader := io.Reader(fileName)
	//
	var row, col int
	fmt.Fscanf(file, "%d %d", &row, &col)
	maze := make([][]int, row)

	for i := range maze {
		maze[i] = make([]int, col)
		for j := range maze[i] {
			fmt.Fscanf(file, "%d", &maze[i][j])
		}
	}
	return maze
}
